﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging; //Remeber to Import
using System.IO; //Remeber to Import
using System.Windows.Printing;
using FluxJpeg.Core;
using System;

namespace VocabCards
{
    public partial class MainPage : UserControl
    {
        private CardCreatorVM _vm;
        public MainPage()
        {
            InitializeComponent();
            DataContext = (_vm = new CardCreatorVM(Dispatcher));
        }

        private void ButtonPrintClick(object sender, RoutedEventArgs e)
        {

            PrintDocument printDocument = new PrintDocument();


            printDocument.BeginPrint += PrintDocumentBeginPrint;
            printDocument.EndPrint += PrintDocumentEndPrint;
            printDocument.PrintPage += PrintDocumentPrintPage;
            printDocument.Print("Word War Cards");

        }


        void PrintDocumentEndPrint(object sender, EndPrintEventArgs e)
        {
            busyIndicator.IsBusy = false;
        }

        void PrintDocumentBeginPrint(object sender, BeginPrintEventArgs e)
        {
            busyIndicator.IsBusy = true;
            _nextCardIndex = 0;
        }

        private int _nextCardIndex = 0;
        void PrintDocumentPrintPage(object sender, PrintPageEventArgs e)
        {

            var page = new PrintDeckControl();

            page.PageMargin = 0;

            //wrap panel isn't showing the correct size
            //lets just calc the size and be done with it
            //margins will be my downfall...
         
            var height = _vm.Cards.First().Height + 5;
            var width = _vm.Cards.First().Width + 5;

            var cardsPerRow = Math.Floor((e.PrintableArea.Width - 2 * page.PageMargin) / width);
            var rowsPerPage = Math.Floor((e.PrintableArea.Height - 2 * page.PageMargin) / height);

            var cardsPerPage = cardsPerRow*rowsPerPage;

            var maxI = _nextCardIndex + cardsPerPage - 1;
            maxI = Math.Min(maxI, _vm.Cards.Count - 1);
            
            for (int i = _nextCardIndex; i <= maxI ; i++)
            {
                page.PageCards.Add(_vm.Cards[i]);
                _nextCardIndex = i + 1;
            }

            e.HasMorePages = _nextCardIndex < _vm.Cards.Count;
 
            e.PageVisual = page;
        }


    }
}
